package ils.domain.issue;

import ils.domain.catalog.model.Book;
import ils.domain.catalog.model.BookRepository;
import ils.domain.model.User;
import ils.domain.model.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.transaction.annotation.Transactional;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import java.text.MessageFormat;

public class BookReleaseProcessorImpl implements BookReleaseProcessor
{
    private static final Logger logger = LoggerFactory.getLogger(BookReleaseProcessorImpl.class);
    private MailSender mailSender;
    private SimpleMailMessage templateMessage;
    private UserRepository userRepository;
    private BookRepository bookRepository;
    @Override
    @Transactional
    public void onMessage(Message arg0)
    {
        try
        {
            MapMessage message = (MapMessage)arg0;
            int bookId = message.getInt("bookId");
            int userId = message.getInt("userId");
            logger.debug("got notification for book: " + bookId);
            sendEmail(userId, bookId);
        }
        catch (JMSException e)
        {
            logger.error("failed to send email", e);
        }
    }
    private void sendEmail(int userId, int bookId)
    {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage(templateMessage);
        User user = userRepository.getUser(userId);
        Book book = bookRepository.getBook(bookId);
        String emailId = user.getEmail();
        simpleMailMessage.setTo(emailId);
        String name = user.getFirstName();
        String bookName = book.getTitle();
        String text =   "Hi {0} \n " + 
                        "You had requested for the book {1} \n" + 
                        "The book is available. Please contact the librarian";
        text = MessageFormat.format(text, name, bookName);
        simpleMailMessage.setText(text);
        mailSender.send(simpleMailMessage);
    }
    public void setMailSender(MailSender mailSender)
    {
        this.mailSender = mailSender;
    }
    public void setTemplateMessage(SimpleMailMessage templateMessage)
    {
        this.templateMessage = templateMessage;
    }
    public void setUserRepository(UserRepository userRepository)
    {
        this.userRepository = userRepository;
    }
    public void setBookRepository(BookRepository bookRepository)
    {
        this.bookRepository = bookRepository;
    }
}
